package com.ziyun.pop.rest.module.capital;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.service.common.protocol.ResultCode;
import com.service.common.utils.Md5Util;
import com.service.ucenter.api.VerifyCodeService;
import com.service.ucenter.constant.UcenterResult;
import com.ziyun.pop.common.utils.UserUtils;
import com.ziyun.pop.modules.capital.entity.MerchantOrderAccountEntity;
import com.ziyun.pop.modules.capital.service.MerchantApplyCashService;
import com.ziyun.pop.modules.capital.service.MerchantApplyLogService;
import com.ziyun.pop.modules.capital.service.MerchantOrderAccountService;
import com.ziyun.pop.modules.supp.entity.SellerInfoEntity;
import com.ziyun.pop.modules.supp.service.SellerInfoService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import io.renren.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zh
 * @date 2019/1/79:32
 */
@Api(value = "ApplyCashRestApi", tags = "提现服务")
@RestController
@RequestMapping("popApi/capital/")
public class ApplyCashRestApi {

    @Autowired
    private MerchantOrderAccountService merchantOrderAccountService;

    @Autowired
    private MerchantApplyCashService merchantApplyCashService;

    @Autowired
    private SellerInfoService sellerInfoService;

    @Autowired
    private VerifyCodeService verifyCodeService;


    @ApiOperation(value = "冻结订单列表")
    @ApiResponses(value = @ApiResponse(code = 200, message = "操作成功"))
    @ApiImplicitParam(name = "params" , paramType = "body",examples = @Example({
            @ExampleProperty(value = "{'user':'id'}", mediaType = "application/json")
    }))
    @PostMapping("/freezeOrderListApi")
    public R freezeOrderListApi(@RequestBody Map<String,Object> params) {
        SysUserEntity sysUser =  UserUtils.getCurentUser();
        params.put("sellerId", sysUser.getSellerId());
        params.put("isFreeze", 0);
        Map<String,Object> rs = this.merchantOrderAccountService.orderList(params);
       return R.apiOk(rs);
    }

    @ApiOperation(value = "可提现订单列表")
    @ApiResponses(value = @ApiResponse(code = 200, message = "操作成功"))
    @PostMapping("/orderListApi")
    public R orderListApi(@RequestBody Map<String,Object> params) {
        SysUserEntity sysUser =  UserUtils.getCurentUser();
        params.put("sellerId", sysUser.getSellerId());
        params.put("isFreeze", 1);
        Map<String,Object> rs = this.merchantOrderAccountService.orderList(params);
        return R.apiOk(rs);
    }

    @ApiOperation(value = "申请提现记录")
    @ApiResponses(value = @ApiResponse(code = 200, message = "操作成功"))
    @PostMapping("/applyCashLogApi")
    public R applyCashLogApi(@RequestBody Map<String,Object> params) {
        SysUserEntity user =  UserUtils.getCurentUser();
        params.put("merchantType", 0);// 存放用户类型
        params.put("sellerId", user.getSellerId());// 存放用户id
        PageUtils page =  this.merchantApplyCashService.queryPage(params);
        return R.apiOk(page);
    }

    @ApiOperation(value = "申请提现发送短信")
    @ApiResponses(value = @ApiResponse(code = 200, message = "操作成功"))
    @PostMapping("/applyCashSendMsg")
    public R applyCashSendMsg() {
        SysUserEntity user =  UserUtils.getCurentUser();
        SellerInfoEntity sellerInfo = this.sellerInfoService.getById(user.getSellerId());
        //校验手机号
        String sellerMobile = sellerInfo.getSellerMobile();
        if (StringUtil.isEmpty(sellerMobile) || sellerMobile.length() !=11){
            throw new RRException("商家手机号异常,请联系管理员!");
        }
        UcenterResult ucenterResult = this.verifyCodeService.getVerifyCode(sellerMobile);
        if (ucenterResult.getCode() == ResultCode.SUCCESS.getCode()){
            return R.apiOk(ucenterResult.getData());
        }else {
            return R.apiError(ucenterResult.getCode(),ucenterResult.getMessage());
        }
    }

    @ApiOperation(value = "申请提现短信验证")
    @ApiResponses(value = @ApiResponse(code = 200, message = "操作成功"))
    @PostMapping("/applyCashCheckMsg")
    public R applyCashCheckMsg(@RequestBody Map<String,Object> params) {
        if (params.get("verifyCode") == null ){
            throw new RRException("请填写验证码!");
        }
        String verifyCode = params.get("verifyCode").toString();
        SysUserEntity user =  UserUtils.getCurentUser();
        SellerInfoEntity sellerInfo = this.sellerInfoService.getById(user.getSellerId());
        //校验手机号
        String sellerMobile = sellerInfo.getSellerMobile();
        if (StringUtil.isEmpty(sellerMobile) || sellerMobile.length() !=11){
            throw new RRException("商家手机号异常,请联系管理员!");
        }
        UcenterResult ucenterResult = this.verifyCodeService.checkVerifyCode(sellerMobile,verifyCode);
        if (ucenterResult.getCode() == ResultCode.SUCCESS.getCode()){
            return R.apiOk(ucenterResult.getData());
        }else {
            return R.apiError(ucenterResult.getCode(),ucenterResult.getMessage());
        }
    }

    @ApiOperation(value = "申请提现")
    @ApiResponses(value = @ApiResponse(code = 200, message = "操作成功"))
    @PostMapping("/applyCashApi")
    public R applyCashApi(@RequestBody Map<String,Object> params) {
        SysUserEntity user =  UserUtils.getCurentUser();
        // 查询待提现订单
        List<Integer> selleInfoIdList = this.merchantOrderAccountService.getSellInfoList(Integer.valueOf(user.getSellerId().toString()));
        List<Map<String,Object>> listMap =  this.merchantOrderAccountService.listMaps(new QueryWrapper<MerchantOrderAccountEntity>()
                .select("(total_amount+cost_freight) amount ,order_account_id orderAccountId")
                .in("seller_id", selleInfoIdList)
                .eq("fund_state", 0) // 仅查询未提现的
                .eq("merchant_type", 0)
                .apply( //日结 非冻结
                        "DATEDIFF(DATE(now()), DATE(received_time)) >= {0} ", 2)
        );
        BigDecimal total = BigDecimal.ZERO;
        List<String> orderAccountIds = new ArrayList<>();
        for (Map<String,Object> map : listMap){
            String orderAccountId = map.get("orderAccountId").toString();
            orderAccountIds.add(orderAccountId);
            BigDecimal amount = new BigDecimal(map.get("amount").toString());
            total = total.add(amount);
        }
        total =  total.setScale(3, BigDecimal.ROUND_HALF_UP);
        BigDecimal totalMoney = new BigDecimal(params.get("totalMoney").toString());
        if (total.compareTo(totalMoney)!=0){
            throw new RRException("传入总金额与后台计算金额有差异,请刷新重试!");
        }
        params.put("orderAccountIds", orderAccountIds.toString());
        params.put("merchantType", 0);// 存放用户类型
        params.put("sellerId", user.getSellerId());
        params.put("userName", user.getUsername());
        this.merchantApplyCashService.applyCash(params);
        return R.apiOk("申请提现成功!");
    }
}
